<?php
namespace App\Http\Controllers\Admin;

use App\User;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Group;
class UsersController extends BaseController
{
    protected $roles;
    public function __construct()
    {
        parent::__construct();
        $userGroup =Group::where('name','=','users')->first();
        $this->roles = $userGroup->group_roles;
    }
    /**
     * 用户列表
     */
    public function index()
    {
        if(!$this->user->can('viewUser')) abort(405);
        
        $listuser = new User(); 
        $userlist = $listuser->getUsersList($this->roles);
        
        return view('admin.users.userlist.index')->with('userlist',$userlist);
    }   
    
    /**
     * 新增
     */
    public function create()
    {
        if(!$this->user->can('editUser')) abort(405);
        
        return view('admin.users.userlist.details')->with('roles',$this->roles);
    }
    
    /**
     * 修改
     */
    public function edit($id)
    {
        if(!$this->user->can('editUser')) abort(405);
        
        $userinfo = User::with('roles')->find($id);
        if(empty($userinfo))
        {
            abort(403);
        }
        $userinfo->userrole = array_fetch($userinfo->roles->toArray(),'id');
        $userinfo->qq = intval(trim($userinfo->qq));
        $userinfo->phone = intval(trim($userinfo->phone));
        $userPath = md5($userinfo->id);
        $logoPath = substr($userPath,0,5).'/'.substr($userPath, 5,10).'/'.substr($userPath, 10).'/';
        $userinfo->logo = '/uploads/avatar/'.$logoPath.'middle.png';
        return view('admin.users.userlist.details')->with('roles',$this->roles)->with('result',$userinfo);
    }
    
    public function show($id)
    {
        
    }
    
    /**
     * 删除
     */
    public function destory($id)
    {
        if(!$this->user->can('deleteUser')) 
            return $this->formatJson('error',$this->permerror);
        
         $userinfo = User::find($id);
         if(!empty($userinfo))
         {
             $userinfo->delete();
             return $this->formatJson('success','删除用户成功！');
         }
         else
         {
             return $this->formatJson('falied','用户不存在！');
         }
             
    }
    
    /**
     * 保存
     */
    public function store(Request $request)
    {
        if(!$this->user->can('editUser'))
            return $this->formatJson('error',$this->permerror);
        
        $this->validate($request, [
            'name'          => 'required|max:255',
            'email'         => 'required|email|max:255',
            'phone'         => 'required|numeric',
            'role_id'       => 'required'
        ]);
        $data = $request->only('name','email','phone','password','repassword','qq','signature','real_name','sex','is_active','userid','role_id');
        if(!empty($data['password']))
        {
           if(trim($data['password']) !== trim($data['repassword']))
             return Response::json(array('status'=>'falied','msg'=>'两次输入的密码不一致，请确认后重试，谢谢！'));
        }
        
        
        if(is_numeric($data['userid'])  && $data['userid'] > 0 )
        {
            $users = User::find($data['userid']);
            if(count($users) <= 0)
            {
                abort(403);
            }
            if(trim($data['email']) !== $users->email)
            {
                $users->email = trim($data['email']);
            }
            if(trim($data['name']) !== $users->name)
            {
                $users->name  = trim($data['name']);
            }
            if($users->phone !== trim($data['phone']))
            {
                $users->phone  = trim($data['name']);
            }
        }
        else
        {
            $users = new User();
            $users->email              = $data['email'];
            $users->phone              = trim($data['phone']);
            $users->name               = trim($data['name']);
        }
        if(!empty(trim($data['password'])))
        {
            $users->password = bcrypt(trim($data['password']));
        }
        $users->qq                 = trim($data['qq']);
        $users->signature          = $data['signature'];
        $users->real_name          = trim($data['real_name']);
        $users->sex                = trim($data['sex']);
        $users->is_active          = trim($data['is_active']);
        DB::beginTransaction();
        try {
            $users->save();
            $users->roles()->sync($data['role_id']);
        }catch (\PDOException $e)
        {
            DB::rollback();
            return Response::json(array('status'=>'falied','msg'=>'用户数据保存失败！'));
        }
        DB::commit();
        return Response::json(array('id'=>$users->id,'status'=>'success','msg'=>'用户数据保存成功！','redirectUrl'=>'/admin/users/users'));
    }
    
    /**
     * 更新用户状态   is_active  0 未激活  1 已激活  2 已关闭
     * @param Request $request
     */
    public function updateStatus(Request $request)
    {
        $id = $request->input('id');
        $is_disabled = $request->input('is_disabled');
        $companyUsers = User::find($id);
    
        if($is_disabled == 1)
        {
            $companyUsers->is_active =2;
        }
        else
        {
            $companyUsers->is_active =1;
        }
        if ($companyUsers->save())
        {
            return  Response::json(array('status'=>'success','msg'=>'用户状态', 'data' => $companyUsers->is_active));
        }
    }
}
